package com.example.schedule.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.airbnb.epoxy.EpoxyController
import com.airbnb.epoxy.EpoxyRecyclerView
import com.airbnb.mvrx.fragmentViewModel
import com.airbnb.mvrx.withState
import com.example.schedule.R
import com.example.schedule.base.MavericksLauncherBaseFragment
import com.example.schedule.databinding.FragmentScheduleBinding
import com.example.schedule.utils.viewBinding
import com.example.schedule.viewmodel.ScheduleViewModel
import com.example.schedule.views.basicRow
import com.example.schedule.views.newDialog

/**
 *Create by Fanketly on 2021/10/31
 *Gitee:https://gitee.com/fanketly
 */
const val TAG = "TAG"

class ScheduleFragment : MavericksLauncherBaseFragment(R.layout.fragment_schedule) {
    private val b: FragmentScheduleBinding by viewBinding()
    private val scheduleViewModel: ScheduleViewModel by fragmentViewModel()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        b.btnSchedule.setOnClickListener {
            newDialog(requireContext()) { b, dialog ->
                b.tvSchedule.setOnClickListener {
                    scheduleViewModel.addSchedule()
                    dialog.dismiss()
                }
                dialog.show()
            }
        }
//        b.rvSchedule.setItemSpacingDp(10)
        b.rvSchedule.buildModelsWith(object : EpoxyRecyclerView.ModelBuilderCallback {
            override fun buildModels(controller: EpoxyController) {
                controller.buildModels()
            }
        })
    }

    private fun EpoxyController.buildModels() = withState(scheduleViewModel) { state ->
        state.scheduleList.forEach {
            basicRow {
                id(it.id)
                margin(10)
                title(it.content)
                subtitle(it.time)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun invalidate() {
        //在此处使用最新状态更新您的视图。每当您的状态发生变化并且 viewLifecycleOwner 已启动时，都会调用此方法。
        b.rvSchedule.requestModelBuild()
    }

}